package com.shareyi.wox.util;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

public class MatchHelper {

	
	public static String methodNameMatcher(String value,Map<String,String> paramMap){
		
		if(StringUtils.isNotEmpty(value)&&value.contains("{")){
			Set<String> list=getKey(value);
			for (String key : list) {
				value=value.replaceAll(getPatternKeyName(key), paramMap.get(key));
			}
			
		}
		
		return value;
	}
	
	
	
	public static String resultUrlMatcher(String value,Map<String,String> paramMap,Map<String,Object> valueContext){
		
		Set<String> keySet=paramMap.keySet();
		for (String key : keySet) {
			value=value.replaceAll(getPatternKeyName(key), paramMap.get(key));
		}
		if(value.contains("{")){
			Set<String> list=getKey(value);
			for (String key : list) {
				if(valueContext.get(key)!=null)
					{
						value=value.replaceAll(getValueContextKeyName(key), valueContext.get(key).toString());
					}
			}
			
		}
		
		return value;
	}
	
	
	
	
	
	public  static String getPatternKeyName(String key){
		return "\\{"+key+"\\}";
	}
	
	
	public  static String getValueContextKeyName(String key){
		return "\\$\\{"+key+"\\}";
	}
	
	public static Set<String>  getKey(String value){
		Set<String> set=new HashSet<String>();
		String key=null;
		String findKey="{";
		int idx=-1;
		int lastIdx=-1;
		while(true){
			 idx=value.indexOf(findKey,lastIdx+1);
			if(idx!=-1){
				if(findKey.equals("}")){
					key=value.substring(lastIdx+1,idx);
					findKey="{";
					set.add(key);
				}else{
					lastIdx=idx;
					findKey="}";
				}
			}else{
				break;
			}	
			
		}
		return set;
	}


}
